<template>
  <div class="all">
    <div class="class">
      <div class="class-header">
        <div class="header-left">
          <div class="line"></div>
          <div class="title">请假记录</div>
          <el-input
            v-model="classSearchInput"
            placeholder="请输入姓名"
            style="width: 150px"
            class="className"
            v-if="role == '1' || role == '2'"
          ></el-input>
           <el-date-picker
            v-model="currentYearMonth"
            type="month"
            placeholder="选择查询时间"
            style="width: 150px"
            value-format="YYYY-MM"
              class="className"
          ></el-date-picker>
          <div style="position: relative">
            <el-button @click="handleSearch" class="search">搜索</el-button>
            <img src="../../assets/images/搜索.png" class="searchImg" alt="" />
          </div>
        </div>
        <div class="header-right">
          <el-button link type="primary" class="addRiBao" @click="handleAddLeave" v-if="role == '3' || role == '4' || role == '5'">申请</el-button>
        </div>
      </div>
    </div>

    <div class="class-content">
      <el-table :data="tableData" style="width: 100%" >
        <el-table-column prop="userName" label="姓名" align="center"  />
        <el-table-column prop="roleName" label="职能" align="center" />
        <el-table-column prop="reason" label="请假事由" align="center" />
        <el-table-column prop="beginTime" label="开始时间" align="center" />
        <el-table-column prop="endTime" label="结束时间" align="center" />
        <el-table-column prop="totalTime" label="请假时长(天)" align="center" />
        <el-table-column prop="status" label="状态" align="center">
          <template #default="{ row }">
            <span :style="{ color: getStatusColor(row.status) }">{{ row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="160">
          <template #default="scope">
            <el-button link type="success" @click="() => updateLeaveData(scope.row)" :disabled="scope.row.status != '正在审核中'">
              修改
            </el-button>
            <el-button link type="danger" @click="deleteLeave(scope.row)" :disabled="scope.row.status != '正在审核中'" >
              撤销
            </el-button>
            <el-button
              link
              type="primary"
              @click="() => handleDetails(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
       <div class="page">
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="currentPage" :page-size="pageSize" @current-change="handleCurrentPageChange" />
        <div> 
            每页
            <el-input-number
              v-model="pageSize"
              :min="1"
              :max="30"
              controls-position="right"
              @change="handleChange"
            />条
</div>

      </div>
    </div>
    <!-- 请假模态框 -->
    <el-dialog v-model="dialogVisible" title="请假申请" width="400px" :show-close="false">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" disabled/>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="date"
              placeholder="请选择开始时间"
              style="width: 200px"
               value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="标识" prop="identity">
            <!-- 下拉框 -->
            <el-select v-model="formData.identity" placeholder="请选择标识" style="width: 200px" disabled >
              <el-option v-for="item in identityOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
          <el-form-item label="返回时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              placeholder="请选择返回时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="请假事由" prop="reason">
            <el-input v-model="formData.reason" />
          </el-form-item>
          <el-form-item label="请假总时长" prop="num" v-if=false>
            <el-input v-model="formData.num" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm" class="confirm">确认</el-button>
      </template>
    </el-dialog>
       <!-- 修改请假模态框 -->
       <el-dialog v-model="dialogVisible2" title="修改请假申请" width="400px" :show-close="false">
      <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        hide-required-asterisk
      >
        <el-row>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" disabled/>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="date"
              placeholder="请选择开始时间"
              style="width: 200px"
               value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="标识" prop="identity">
            <!-- 下拉框 -->
            <el-select v-model="formData.identity" placeholder="请选择标识" style="width: 200px" disabled >
              <el-option v-for="item in identityOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </el-form-item>
          <el-form-item label="返回时间" prop="endTime">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              placeholder="请选择返回时间"
              style="width: 200px"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="请假事由" prop="reason">
            <el-input v-model="formData.reason" />
          </el-form-item>
          <el-form-item label="请假总时长" prop="num" v-if=false>
            <el-input v-model="formData.num" />
          </el-form-item>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible2 = false" class="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm1" class="confirm">确认</el-button>
      </template>
    </el-dialog>
    <!-- 展示请假模态框 -->
    <el-drawer  v-model="dialogVisible1" title="请假详情信息" size="700" :show-close="false" style="background-color:#F0F8FF;height:100%">
      <div class="richang">
        <div class="name">
          <span class="name1">姓 名：</span>
          <span class="name2">{{ selectedRow.userName }}</span>
        </div>
        <div class="name">
          <span class="name1">职 能：</span>
          <span class="name2">{{ selectedRow.roleName }}</span>
        </div>
        <div class="name">
          <span class="name1">开始时间：</span>
          <span class="name2">{{ selectedRow.beginTime }}</span>
        </div>
        <div class="date">
          <span class="date1">结束时间：</span>
          <span class="date2">{{ selectedRow.endTime }}</span>
        </div>
        <div class="name">
          <span class="name1">请假时长：</span>
          <span class="name2">{{ selectedRow.totalTime }}</span>
        </div>
        <div class="name">
          <span class="name1">状 态：</span>
          <span :style="{ color: getStatusColor(selectedRow.status) }">{{ selectedRow.status }}</span>
        </div>
        <div class="content">
          <span class="content1">请假事由：</span>
          <span class="content2" v-html="selectedRow.reason"></span>
        </div>


       
      </div>
      <template #footer>
        <el-button @click="dialogVisible1 = false" class="confirm">关闭</el-button>
      </template>
    </el-drawer >
  </div>
</template>
    
  <script setup>
import { ref, onMounted } from 'vue'
import { getLeave ,getIdentity,postLeave,getLeaveInfo,updateLeave,revokeLeave} from '../api/Leave'
import { ElMessage ,ElMessageBox} from 'element-plus'
import dayjs from 'dayjs' // 引入 dayjs 库

//本地存储
const user = JSON.parse(localStorage.getItem('user'))

//获取角色信息
const role =  user.roleId
// 定义当前年月
const currentYearMonth = ref('')
// 定义日期选择器的引用
const datePickerRef = ref(null)
// 定义搜索框输入的值
const classSearchInput = ref('')
// 定义当前页
const currentPage = ref(1)
// 定义每页显示的条数
const pageSize = ref(7)
// 定义总条数
const total = ref(0)
// 选中的本行数据
const selectedRow = ref()
//获取请假列表
function fetchData() {
  const data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    // thisMonth: currentYearMonth.value,
    // userName: classSearchInput.value,
  }
  if (classSearchInput.value) {
    data.userName = classSearchInput.value
  }
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  getLeave('leavesList', data).then((res) => {
    if (res.code == 200) {

      tableData.value = res.dataset.leaveList
      total.value = res.dataset.pageCount * pageSize.value
    }
   
  })
}

//个人请假信息
function getLeaveInfo1(){
  const data = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    userId: user.userId,
    roleId: role,
  } 
  if (currentYearMonth.value) {
    data.thisMonth = currentYearMonth.value
  }
  getLeaveInfo('leavesListPersonal', data).then((res) => {
    if (res.code == 200) {
      tableData.value = res.dataset.leaveList
      total.value = res.dataset.pageCount * pageSize.value
    }

  })
}

// 处理当前页变化
const handleCurrentPageChange = (value) => {
  currentPage.value = value
  if (role == '1' || role == '2') {
    fetchData() 
  }else{
    getLeaveInfo1()
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置当前页为第一页
  if (role == '1' || role == '2') {
    fetchData() 
  }else{
    getLeaveInfo1()
  }
}

// 身份下拉框数据
const identityOptions = ref([])
// 获取身份下拉框数据
function getIdentityData() {
  let data = {}
  getIdentity('roleList',data).then((res) => {
    identityOptions.value = res.dataset
  }) 
}

onMounted(() => {
  if (role == '1' || role == '2') {
     fetchData()
  }else{
    getLeaveInfo1()
  }
 
  getIdentityData()
})



// 表格数据
const tableData = ref([])
// 状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case '通过':
      return 'green'
    case '不通过':
      return 'red'
    case '正在审核中':
      return 'blue'
    default:
      return 'black'
  }
}



// 新增：写日报模态框
const dialogVisible = ref(false)
const formRef = ref(null)
// 新增：写日报表单数据
const formData = ref({
  name: '',
  identity: '',
  reason: '',
  startTime: '',
  endTime: '',
  num: '',
})
// 点击按钮触发
const handleAddLeave = () => {
  if(formRef.value){
    formRef.value.clearValidate() 
  }
  formData.value = {
    name: user.userName, // 姓名
    identity: role, // 标识
    reason: '', // 请假事由
    startTime: '', // 开始时间
    endTime: '', // 结束时间
    num: '', // 请假总时长
  }
  dialogVisible.value = true
}
// 新增验证函数：开始时间不能早于当天
const validateStartAfterToday = (rule, value, callback) => {
  const today = dayjs().startOf('day')
  const selectedDate = dayjs(value).startOf('day')
  
  if (selectedDate.isBefore(today)) {
    callback(new Error('开始时间不能早于当天'))
  } else {
    callback()
  }
}
// 自定义验证函数：开始时间必须在结束时间之前
const validateStartTime = (rule, value, callback) => {
  if (formData.value.endTime && value) {
    const endTime = dayjs(formData.value.endTime)
    const startTime = dayjs(value)
    if (endTime.isBefore(startTime)) {
      callback(new Error('开始时间必须在结束时间之前'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

// 自定义验证函数：结束时间必须在开始时间之后
const validateEndTime = (rule, value, callback) => {
  if (formData.value.startTime && value) {
    const startTime = dayjs(formData.value.startTime)
    const endTime = dayjs(value)
    if (endTime.isBefore(startTime)) {
      callback(new Error('结束时间必须在开始时间之后'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

// 计算请假总时长
const calculateNum = () => {
  if (formData.value.startTime && formData.value.endTime) {
    const startTime = dayjs(formData.value.startTime)
    const endTime = dayjs(formData.value.endTime)
    const days = endTime.diff(startTime, 'day')
    formData.value.num = days.toString()
  }
}

// 计算结束时间
const calculateEndTime = () => {
  if (formData.value.startTime && formData.value.num) {
    const startTime = dayjs(formData.value.startTime)
    const endTime = startTime.add(parseInt(formData.value.num), 'day')
    formData.value.endTime = endTime.format('YYYY-MM-DD')
  }
}

// 计算开始时间
const calculateStartTime = () => {
  if (formData.value.endTime && formData.value.num) {
    const endTime = dayjs(formData.value.endTime)
    const startTime = endTime.subtract(parseInt(formData.value.num), 'day')
    formData.value.startTime = startTime.format('YYYY-MM-DD')
  }
}

// 新增：写请假表单验证规则
const rules = {
   name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  identity: [{ required: true, message: '请选择标识', trigger: 'change' }],
  reason: [{ required: true, message: '请输入请假事由', trigger: 'blur' }],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' },
    { validator: validateStartAfterToday, trigger: 'change' },  // 新增验证规则
    { validator: validateStartTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.value.endTime) {
          calculateNum()
        } else if (value && formData.value.num) {
          calculateEndTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    { validator: validateEndTime, trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && formData.value.startTime) {
          calculateNum()
        } else if (value && formData.value.num) {
          calculateStartTime()
        }
        callback()
      },
      trigger: 'change',
    },
  ],
  num: [
    { required: true, message: '请输入请假总时长', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (formData.value.startTime && value) {
          calculateEndTime()
        } else if (formData.value.endTime && value) {
          calculateStartTime()
        }
        callback()
      },
      trigger: 'blur',
    },
  ],
}

//提交请假接口
function postLeaveData() {
  const data = {
    userId: user.userId, // 用户ID 
    userName: user.userName, // 姓名
    roleId: role, // 标识
    beginTime: formData.value.startTime, // 开始时间
    endTime: formData.value.endTime, // 结束时间
    totalTime: Number(formData.value.num), // 请假总时长
    reason: formData.value.reason, // 请假事由
  } 
  postLeave('addLeave',data).then((res) => {
      if(res.code == 200){
        ElMessage.success('提交成功')
        dialogVisible.value = false
        if (role == '1' || role == '2') {
          fetchData() 
        }else{
          getLeaveInfo1()
        }
      }
  })
}
//修改请假接口
function updateLeaveData1(){
  const data = {
    userId: user.userId, // 用户ID
    userName: user.userName, // 姓名
    roleId: role, // 标识
    beginTime: formData.value.startTime, // 开始时间
    endTime: formData.value.endTime, // 结束时间
    totalTime: Number(formData.value.num), // 请假总时长
    reason: formData.value.reason, // 请假事由
    leaveId: formData.value.leaveId, // 请假ID
  }
  updateLeave('updateLeave',data).then((res) => {
    if(res.code == 200){
        ElMessage.success('提交成功')
        dialogVisible2.value = false
        if (role == '1' || role == '2') {
          fetchData() 
        }else{
          getLeaveInfo1()
        }
      }
  })
}
//撤销
function revokeLeaveData(leaveId){
  const data = {
    leaveId: leaveId, // 请假ID
  }
  revokeLeave('deleteLeave',data).then((res) => {
    if(res.code == 200){
        ElMessage.success('撤销成功')
        if (role == '1' || role == '2') {
          fetchData()
        } else {
          getLeaveInfo1()
        }
    }
  })
}

// 新增：请假表单提交
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否提交？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning', 
      }).then(() => {
        postLeaveData()
      }).catch(() => {
        ElMessage.info('已取消')
      })
    }
  })
}

const dialogVisible1 = ref(false)
// 处理表格行点击事件
// const handleRowClick = (row) => {
//   selectedRow.value = row
//   dialogVisible1.value = true
// }

// 处理详情
const handleDetails = (row) => {
  selectedRow.value = row
  dialogVisible1.value = true
}
// 处理取消
const dialogVisible2 = ref(false)
const updateLeaveData = (row) => {
  dialogVisible2.value = true
  console.log(row);
  if(role == '1' || role == '2'){
    formData.value = {
      name: row.userName, // 姓名
      identity: row.roleId, // 标识
      reason: row.reason, // 请假事由
      startTime: row.beginTime, // 开始时间
      endTime: row.endTime, // 结束时间
      num: row.totalTime, // 请假总时长
      leaveId: row.leaveId, // 请假ID
    }
  }else{
    formData.value = {
    name: user.userName, // 姓名
    identity: role, // 标识
    reason: row.reason, // 请假事由
    startTime: row.beginTime, // 开始时间
    endTime: row.endTime, // 结束时间
    num: row.totalTime, // 请假总时长
    leaveId: row.leaveId, // 请假ID
  }
  }
 
}

// 处理修改
const handleConfirm1 = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('是否修改？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        updateLeaveData1()
      }).catch(() => {
        ElMessage.info('已取消')
      })
    }
  })
}
// 处理撤销
const deleteLeave = (row) => {
  ElMessageBox.confirm('是否撤销请假？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    revokeLeaveData(row.leaveId)
  }).catch(() => {
    ElMessage.info('已取消')
  })
}

function handleChange(){
  if (role == '1' || role == '2') {
    fetchData()
  }else{
    getLeaveInfo1()
  }
}


</script>
    
  <style scoped>
.class {
  width: 90%;
  height: 10%;
  margin-bottom: 20px;
  margin-top: 20px;
}
/* 头部左侧 */
.header-left {
  display: flex;
  align-items: center;
  margin-left: 40px;
}
.line {
  width: 2px;
  height: 20px;
  background-color: #007bff;
}
.title {
  padding-left: 10px;
  font-size: 20px;
  margin-right: 20px;
}
.className {
  margin-right: 10px;
}
.line2 {
  width: 10px;
  height: 2px;
  margin-left: 5px;
  margin-right: 5px;
  background-color: #9b9b9b;
}
:deep(.className .el-input__wrapper){
  border-radius: 12px !important;
}
.search {
  background-color: #0f6ab1;
  color: #fff;
  border: none;
  margin-left: 10px;
  border-radius: 16px;
  padding: 0;
  padding-right: 15px;
  padding-left: 36px;
}
.searchImg {
  position: absolute;
  top: 8px;
  left: 25px;
}
/* 头部右侧 */
.header-right {
  display: flex;
  align-items: center;
  margin-right: 40px;
}
.currentTime {
  font-size: 15px;
  margin-right: 10px;
}
.calendar-icon {
  display: flex;
  align-items: center;
}
.custom-calendar-icon {
  font-size: 20px; /* 可以根据需要调整图标大小 */
}
.addRiBao {
  margin-left: 10px;
  font-size: 15px;
}

/* 表格区域 */
.class-content {
  width: 90%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格数据 */
:deep(.el-table thead th) {
  background-color: #fbfcff !important;
}
:deep(.el-table .cell) {
  color: black;
}
:deep(.details1) {
  margin-left: 55px;
}
/* 报告不能换行 */
:deep(.el-table__body-wrapper .cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* 分页 */
.page {
  margin-top: 50px;
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}
/* 分页背景色 */
:deep(.el-pager .is-active) {
  background-color: #0f6ab1 !important;
}
/* 模态框 */
:deep(.el-overlay .el-overlay-dialog) {
  position: absolute;
}
:deep(.el-overlay) {
  position: absolute;
}
:deep(.el-dialog__body){
  display: flex;
  justify-content: center;
}
:deep(.el-dialog) {
  padding: 0px;
  width: 800px;
}
:deep(.el-dialog header span) {
  display: inline-block;
  width: 100%;
  background-color: #0f6ab1;
  height: 40px;
  color: white;
  font-size: 15px;
  text-align: center;
  line-height: 40px;
}
:deep(.el-dialog__footer) {
  text-align: center;
  padding-bottom: 20px;
}
:deep(.confirm) {
  margin-left: 50px;
  background-color: #0f6ab1;
}
:deep(.cancel) {
  background-color: #0f6ab1;
  color: white;
}
:deep(.el-drawer header) {
  background-color: #0f6ab1;
  margin-bottom: 0;
  padding-bottom: 20px;
}
:deep(.el-drawer header span) {
  color: white;
}

:deep(.el-drawer__header span){
  text-align: center;
  color: black;
  font-size: 20px;
}
:deep(.w-e-scroll p) {
  margin: 0;
}
:deep(.confirm) {
  color: white;
  margin-left: 50px;
  background-color: #0f6ab1;
}
.name,
.content,
.date {
  color: black;
  font-size: 15px;
  margin-left: 20px;
  margin-bottom: 20px;
}
</style>